package com.cwt_taxi_xa.protocol.socket;

import com.cwt_taxi_xa.MainApplication;
import com.cwt_taxi_xa.data.SocketConfig;
import com.cwt_taxi_xa.util.AppLog;
import com.cwt_taxi_xa.util.Tools;


/**
 * Created by undi on 2019/8/24/020.
 */

public class SocketClient  implements MessageAssembly.MessageCallback,MessageClient{

    private String TAG = "SocketClient";
    // ----------------------------------------------------------------------------
    //905编码解码类
    // ----------------------------------------------------------------------------
    Decoder mDecoder = new Decoder(this,new BusinessProcessSZ(this));

    Encoder mEncoder = new Encoder();

    // ----------------------------------------------------------------------------
    //Netty客户端&消息粘包处理
    // ----------------------------------------------------------------------------
    DispatchCenterClient mDispatchCenterClient = new DispatchCenterClient(this);

    MessageAssembly.MessageCallback messageCallback2 = new MessageAssembly.MessageCallback() {
        @Override
        public void callback(byte[] data) {
            mDecoder.decoderQH808Data(data, MainApplication.getInstance());
        }
    };
    MessageAssembly messageAssembly = new MessageAssembly(messageCallback2);

    /**
     * 配置参数
     */
    public void create(SocketConfig socketConfig) {
        mDispatchCenterClient.setSocketConfig(socketConfig);
    }
    /**
     * socket粘包处理回调
     * @param data TCP/TP收到的数据
     * {@link #mDispatchCenterClient}.
     */
    @Override
    public void callback(byte[] data) {
        messageAssembly.nb_center(data);
    }


    @Override
    public Encoder getEncoder() {
        return mEncoder;
    }

    @Override
    public Decoder getDecoder() {
        return mDecoder;
    }

    public void setConnect(SocketConfig mSocketConfig){
        mDispatchCenterClient.setSocketConfig(mSocketConfig);
    }

    public void setConnect(boolean connected){
        mDispatchCenterClient.setConnect(connected);
    }

    /**
     * 往平台发送消息
     */
    @Override
    public void sendMessage(byte[] data){
        AppLog.d(TAG,"sendMessage:" + Tools.parseByte2HexStr(data));
        mDispatchCenterClient.writeMsg(data);
    }

    /**
     * 不带905协议的数据
     * 主要上传位置信息
     * @param data
     */
    public void sendDataMessage(byte[] data){
        sendMessage(getEncoder().getLocationInformation(data));
    }

    /**
     * 发送心跳
     */
    public void sendHeartbeatMessage(){
        sendMessage(getEncoder().getHeartbeat());
    }


}
